package com.letoy.edu.config.auth;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.letoy.edu.entity.TokenInfo;
import com.letoy.edu.service.TokenService;
import com.letoy.edu.service.UserService;
import com.letoy.edu.utils.JwtTokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功操作
 */
@Component
public class MyAuthenticationSuccessHandler extends JSONAuthentication implements AuthenticationSuccessHandler {

    @Resource
    UserService userService;

    @Resource
    TokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        //取得账号信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //
        System.out.println("userDetails = " + userDetails);
        //取token
        //好的解决方案，登录成功后token存储到数据库中
        //只要token还在过期内，不需要每次重新生成
        System.out.println("登录成功");
        String id = userService.getUserIdByNamePassword(userDetails.getUsername(), userDetails.getPassword());
        String token = tokenService.getTokenByUserId(id).getSystemToken();
        System.out.println("当前的token是：" + token);
        if (token == null| token.equals("")) {
            System.out.println("初次登录，token还没有，生成新token。。。。。。");
            //如果token为空，则去创建一个新的token
            jwtTokenUtil = new JwtTokenUtil();
            token = jwtTokenUtil.generateToken(userDetails);
            //把新的token存储到缓存中
            TokenInfo tokenInfo = new TokenInfo();
            tokenInfo.setUserId(id);
            System.out.println(token);
            tokenInfo.setSystemToken(token);
            tokenService.updateTokenInfo(tokenInfo);
        }

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = new HashMap<>();
        map.put("username", userDetails.getUsername());
        map.put("auth", userDetails.getAuthorities());
//        map.put("menus",menus);
        map.put("token", token);
        //输出
        this.WriteJSON(request, response, map);

    }
}
